package com.project.controller;

import com.project.baseInfo.dto.UserDto;
import com.project.baseInfo.model.LoginUserInfo;
import com.project.baseInfo.model.Result;
import com.project.baseInfo.model.User;
import com.project.baseInfo.vo.UserVo;
import com.project.constants.SessionConstants;
import com.project.service.UserService;
import com.project.service.proxy.LogJDKHandler;
import com.project.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    private static Logger log=LoggerFactory.getLogger(UserController.class);

    @Autowired // 先byType再byName
    @Qualifier("userServiceImpl") // 如果字段名改成userServiceImpl也可以不加@Qualifier
//    @Resource(name = "userServiceImpl") // 先byName再byType，等同于上面两个注解
    private UserService userService;

    @Autowired
    private LogJDKHandler logJDKHandler;

    @Resource(name = "userServiceImplProxy")
    private UserService userServiceProxy; // 静态代理类，名字跟spring bean配置的id一样

    @ResponseBody
    @RequestMapping(value = "/registerUser.do", method = RequestMethod.POST)
    public Result<String> registerUser(HttpServletRequest request, UserDto user) {
        Result<String> result;
        if (null == user){
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("入参不能为空");
            return result;
        }
        if (StringUtils.isEmpty(user.getUserName())){
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("用户名不能为空");
            return result;
        }
        if (StringUtils.isEmpty(user.getPassword())){
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("密码不能为空");
            return result;
        }
        try {
            result = userServiceProxy.registerUser(user);
        }catch (Exception e){
            log.error("保存用户异常：",e);
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("注册用户异常");
            return result;
        }
        return result;
    }

    @RequestMapping(value="/userGetPage.do",method=RequestMethod.GET)
    public String userGetPage(HttpServletRequest request, Model model){
        return "userManage/userGetPage";
    }

    @ResponseBody
    @RequestMapping(value = "/userGetData.do", method = RequestMethod.POST)
    public Result<List<UserVo>> userGetData(HttpServletRequest request, UserDto user) {
        Result<List<UserVo>> result;
        if (null == user){
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("入参不能为空");
            return result;
        }
        try {
            // jdk动态代理
            UserService userServiceJDKProxy = (UserService) logJDKHandler.newProxyInstance(userService);
            result = userServiceJDKProxy.queryUserPage(user);
//            result = userService.queryUserPage(user);
        }catch (Exception e){
            log.error("查询用户列表异常：",e);
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("查询用户列表异常");
            return result;
        }
        return result;
    }

    @ResponseBody
    @RequestMapping(value = "/deleteUser.do", method = RequestMethod.POST)
    public Result<String> deleteUser(HttpServletRequest request, UserDto userDto) {
        Result<String> result;
        try {
            // 从sesion中获得用户数据返回到页面
            LoginUserInfo loginUserInfo = (LoginUserInfo) request.getSession().getAttribute(SessionConstants.USER);
            if (loginUserInfo == null){
                result = new Result<>();
                result.setCode(Result.FAIL);
                result.setInfo("获取用户失败");
                return result;
            }
            if (null == userDto){
                result = new Result<>();
                result.setCode(Result.FAIL);
                result.setInfo("入参不能为空");
                return result;
            }
            if (StringUtils.isEmpty(userDto.getUserIds())){
                result = new Result<>();
                result.setCode(Result.FAIL);
                result.setInfo("用户id不能为空");
                return result;
            }
            List<String> userIdStrList = Arrays.asList(userDto.getUserIds().split(","));
            List<Long> userIdList = new ArrayList<>();
            userIdStrList.forEach(userId -> userIdList.add(Long.valueOf(userId)));
            userDto.setUserIdList(userIdList);
            userDto.setUpdateUserId(loginUserInfo.getId());
            result = userService.deleteUserByIdList(userDto);
        }catch (Exception e){
            log.error("删除用户异常：",e);
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("删除用户异常");
            return result;
        }
        return result;
    }

    @RequestMapping(value="/addUserGetPage.do",method=RequestMethod.GET)
    public String addUserGetPage(HttpServletRequest request, Model model){
        return "userManage/userAdd";
    }

    @RequestMapping(value="/editUserGetPage.do",method=RequestMethod.GET)
    public String editUserGetPage(HttpServletRequest request, Model model, UserDto userDto){
        User user = userService.getUserById(userDto.getId());
        model.addAttribute("pageType","edit");
        model.addAttribute("userName",user.getUserName());
        model.addAttribute("id",user.getId());
        model.addAttribute("birthday", DateUtils.formatDate(user.getBirthday()));
        model.addAttribute("idCard",user.getIdCard());
        model.addAttribute("phoneNum",user.getPhoneNum());
        model.addAttribute("realName",user.getRealName());
        model.addAttribute("sex",user.getSex());
        return "userManage/userAdd";
    }

    @ResponseBody
    @RequestMapping(value = "/updateUser.do", method = RequestMethod.POST)
    public Result<String> updateUser(HttpServletRequest request, UserDto userDto) {
        Result<String> result;
        try {
            // 从sesion中获得用户数据返回到页面
            LoginUserInfo loginUserInfo = (LoginUserInfo) request.getSession().getAttribute(SessionConstants.USER);
            if (loginUserInfo == null){
                result = new Result<>();
                result.setCode(Result.FAIL);
                result.setInfo("获取用户失败");
                return result;
            }
            if (null == userDto){
                result = new Result<>();
                result.setCode(Result.FAIL);
                result.setInfo("入参不能为空");
                return result;
            }
            if (StringUtils.isEmpty(userDto.getUserName())){
                result = new Result<>();
                result.setCode(Result.FAIL);
                result.setInfo("用户名不能为空");
                return result;
            }
            userDto.setUpdateUserId(loginUserInfo.getId());
            // TODO cglib动态代理调用 获取不到userDao对象的值
//            UserManager userManagerCglibProxy = (UserManager) Enhancer.create(UserManager.class, new LogCglibInterceptor());
//            result = userManagerCglibProxy.updateUser(userDto);
            result = userService.updateUser(userDto);
        }catch (Exception e){
            log.error("删除用户异常：",e);
            result = new Result<>();
            result.setCode(Result.FAIL);
            result.setInfo("删除用户异常");
            return result;
        }
        return result;
    }
}
